package srst.util.PDFHandleUtil;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;


import srst.util.FilePathUtil;

/**
 * @author 作者 : YUHU YUAN
 * @date 创建时间：2017年5月23日 下午11:23:19
 * @version 1.0
 */

public class ExtractImages {

	public void checkSaveResources(PDResources resources) throws IOException {
		if (resources == null) {
			return;
		}
		for (COSName name : resources.getXObjectNames()) {
			PDXObject xobject = resources.getXObject(name);
			if (xobject instanceof PDImageXObject) {
				PDImageXObject imageObject = (PDImageXObject) xobject;
				String suffix = imageObject.getSuffix();
				if (suffix != null) {
					if ("jpx".equals(suffix)) {
						suffix = "JPEG2000";
					}
					if ("jb2".equals(suffix)) {
						// jbig2 usually not available
						suffix = "PNG";
					}
					FileOutputStream pw  = new FileOutputStream("D:/test.jpg");
					boolean writeOK = ImageIOUtil.writeImage(imageObject.getImage(), suffix, pw);
					System.out.println(writeOK);
				}
			} else if (xobject instanceof PDFormXObject) {
				checkSaveResources(((PDFormXObject) xobject).getResources());
			}
		}
	}

	public void getTextFromPDF(String pdfFilePath) throws IOException {
		PDDocument document = null;
		try {
			RandomAccessRead randomAccessRead = new RandomAccessBufferedFileInputStream(pdfFilePath);
			PDFParser parser = new PDFParser(randomAccessRead);
			parser.parse();
			document = parser.getPDDocument();
			System.out.println(document.getNumberOfPages());
			PDPage page = document.getPage(0);
			PDResources resources = page.getResources();
			checkSaveResources( resources);
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

	public static void main(String[] args) {
		ExtractImages test = new ExtractImages();
		try {
			test.getTextFromPDF(FilePathUtil.TEXT_PATH);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		

	}

}











